package cn.project.engineering.base

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.res.Resources
import android.graphics.Point
import android.graphics.Rect
import android.os.Bundle
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import cn.project.engineering.BuildConfig
import cn.project.engineering.constant.LiveEventBusConstant
import cn.project.engineering.http.HttpClient
import cn.project.engineering.http.RequestCallback
import cn.project.engineering.http.bean.ApkInfo
import cn.project.engineering.http.bean.PassInfor
import cn.project.engineering.http.bean.RequestError
import cn.project.engineering.receiver.NetWorkBroadCastReceiver
import cn.project.engineering.utils.*
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.jeremyliao.liveeventbus.LiveEventBus
import com.mstar.android.tv.TvPictureManager
import log.KLog
import java.io.File


/**
 *
 * @author  zhengpeng  v001 Android 6.0
 * @date 2021年3月8日
 */
abstract class MyAppCompatActivity : AppCompatActivity() {
    companion object {
        private const val TAG = "MyAppCompatActivity"
    }
    //    private var adminReceiver: ComponentName? = null
//    private var policyManager: DevicePolicyManager? = null
//    private var powerManager: PowerManager? = null
//    private var wakeLock: PowerManager.WakeLock? = null
    var loading=false
    var permission_array:Array<String> = arrayOf(Permission.MANAGE_EXTERNAL_STORAGE,Permission.REQUEST_INSTALL_PACKAGES)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

//        toast("--"+isShowNavBar(this))
//        //检查升级
//        checkApkInfor()
//        policyManager = getSystemService(DEVICE_POLICY_SERVICE) as DevicePolicyManager
//        powerManager = getSystemService(POWER_SERVICE) as PowerManager
//        adminReceiver = ComponentName(this, ScreenOffAdminReceiver::class.java)
//        checkAndTurnOnDeviceManager();
        AppUtils.hideInput(this)
        val intentFilter = IntentFilter()
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE")
        val networkChangeReceiver = NetWorkBroadCastReceiver()
        registerReceiver(networkChangeReceiver, intentFilter) //注册广播接收器，接收CONNECTIVITY_CHANGE这个广播


        LiveEventBus.get(LiveEventBusConstant.OPEN_SCREEN_EVENT, String::class.java).observe(this, object : Observer<String> {
            override fun onChanged(t: String?) {

                // 开启屏幕
                KLog.d("屏幕", "打开屏幕")

                gwScreenOn()
            }

        })
        LiveEventBus.get(LiveEventBusConstant.CLOSE_SCREEN_EVENT, String::class.java).observe(this,object : Observer<String> {
            override fun onChanged(t: String?) {
                gwScreenOff()
                // 开启屏幕
                KLog.d("屏幕", "关闭屏幕")

            }

        })
        LiveEventBus.get(LiveEventBusConstant.INTERNET, String::class.java).observe(this, object : Observer<String> {
            override fun onChanged(t: String?) {
                if (t.equals("0")) {
                    netWork(false)
                }else{
                    netWork(true)
                }

//                    var net= AppUtils.netWorkCheck(this@MyAppCompatActivity)

//                if (net){
//                    toast("有网络")
//                }else{
//                    toast("无网络")
//                }
//                        }
            }

        })
        LiveEventBus.get(LiveEventBusConstant.UPDATE, String::class.java).observe(this,object : Observer<String> {
            override fun onChanged(data: String?) {
                data?.let { instal(it)
                }
            }
        })

        var  ostype=WonderSp.getDataNomal(this@MyAppCompatActivity,"ostype");
        when (ostype) {
            "V001" -> {
                //com.slx.show显示底部菜单 com.slx.hide隐藏底部菜单
//                val intent = Intent()
//                intent.action="com.slx.hide"
//                this@MyAppCompatActivity.sendBroadcast(intent)
                hideBar()
            }
            "V002" -> {


            }
        }
    }

//    /**
//     * 熄屏
//     */
//    open fun screenOff() {
//        adminReceiver?.let {
//            if (true == policyManager?.isAdminActive(it)) {
//                val isScreenOn = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT_WATCH) {
//                    powerManager?.isInteractive
//                } else {
//                    powerManager?.isScreenOn
//                }
//
//                if (true == isScreenOn) {
//                    policyManager?.lockNow()
//                }
//            } else {
//                KLog.d(TAG, "没有设备管理权限")
//            }
//        }
//    }

    //    /**
//     * 亮屏
//     */
//    @SuppressLint("InvalidWakeLockTag")
//    open  fun screenOn() {
//        val isScreenOn = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT_WATCH) {
//            powerManager?.isInteractive
//        } else {
//            powerManager?.isScreenOn
//        }
//
//        if (true != isScreenOn) {
//            wakeLock = powerManager?.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP, "bright")
//            // 点亮屏幕
//            wakeLock?.acquire(1000)
//            // 释放
//            wakeLock?.release()
//
//            // 屏幕解锁
//            val keyguardManager = getSystemService(KEYGUARD_SERVICE) as KeyguardManager
//            val keyguardLock = keyguardManager.newKeyguardLock("unLock")
//            // 解锁
//            keyguardLock.disableKeyguard()
//        }
//    }
    //检查更新
    fun checkApkInfor() {
        XXPermissions.with(this).permission(permission_array)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: List<String>, all: Boolean) {
                        if (all) {
                            HttpClient.httpService().checkApk().enqueue(object : RequestCallback<List<ApkInfo>> {
                                override fun onRequestSuccess(body: List<ApkInfo>?) {
                                    body?.let {
                                        if (it.isNotEmpty()) {
                                            val apkInfo = it[0]
                                            if (apkInfo.UnitName.toInt()>AppUtils.getVersionCode(this@MyAppCompatActivity)){
                                                Thread(object : Runnable{
                                                    override fun run() {
                                                        DownloadUtil.get().download(apkInfo.APK,PathUtil.BASE_FILE_URL,"gwesop.apk",object :DownloadUtil.OnDownloadListener{
                                                            override fun onDownloadSuccess(file: File?) {
                                                                runOnUiThread(object :Runnable{
                                                                    override fun run() {
                                                                        toast("下载完成")
                                                                    }
                                                                })

                                                                KLog.debug(TAG,"onDownloadSuccess")
//                                                                AppUtils.installApk(this@MyAppCompatActivity)
                                                                var  ostype=WonderSp.getDataNomal(this@MyAppCompatActivity,"ostype");
                                                                when (ostype) {
                                                                    "V001" -> {
                                                                        val intent = Intent()
                                                                        intent.action = "com.slx.InstallSlient"
                                                                        intent.putExtra("path", PathUtil.BASE_FILE_URL + "/gwesop.apk")
                                                                        this@MyAppCompatActivity.sendBroadcast(intent)
                                                                    }
                                                                    "V002" -> {
//                                                                        runOnUiThread(object :Runnable{
//                                                                            override fun run() {
//                                                                                toast(PathUtil.BASE_FILE_URL + "/gwesop.apk")                                                                    }
//                                                                        })
                                                                        val intent = Intent()
                                                                        intent.action="cms.intent.action.UPDATE_APK"
                                                                        intent.putExtra("filePath", PathUtil.BASE_FILE_URL + "/gwesop.apk")
                                                                        intent.putExtra("keep",true)
                                                                        intent.putExtra("packageName", "cn.project.engineering")
                                                                        intent.putExtra("activityName", "cn.project.engineering.ui.SplashActivity")
                                                                        this@MyAppCompatActivity.sendBroadcast(intent)

                                                                    }
                                                                }
                                                                loading=false;
                                                            }
                                                            override fun onDownloadFailed(e: Exception?) {
                                                                runOnUiThread(object :Runnable{
                                                                    override fun run() {
                                                                        toast("下载失败")                                                                    }
                                                                })

                                                                KLog.debug(TAG,"onDownloadFailed"+e.toString())
                                                                loading=false;
                                                            }

                                                            override fun onDownloading(progress: Int) {
//                                                                runOnUiThread(object :Runnable{
//                                                                    override fun run() {
//                                                                        toast("正在下载进度" + progress)
//                                                                    }
//                                                                })

                                                                loading=true

                                                                KLog.debug(TAG,"onDownloading"+Int)
                                                            }

                                                        })
                                                    }
                                                }).start()

                                            }

                                        }else{

                                        }
                                    }

                                }

                                override fun onRequestFail(error: RequestError) {

                                }

                            })

                        }
                    }

                    override fun onDenied(permissions: List<String>, never: Boolean) {
                        for (i in permissions.indices) {
                            val permission = permissions[i]
                            toast("${permission}权限未允许，请重新选择")
                        }
                    }
                })

    }
//    /**
//     * 激活设备管理权限
//     */
//    private fun checkAndTurnOnDeviceManager() {
//        adminReceiver?.let {
//            if (true != policyManager?.isAdminActive(it)) {
//                KLog.d(TAG, "设备管理权限未激活")
//                try {
//                    val intent = Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN)
//                    intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, adminReceiver)
//                    intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "开启后就可以使用锁屏功能了...")
//                    startActivityForResult(intent, 0)
//                } catch (e: ActivityNotFoundException) {
//
//                }
//            } else {
//                KLog.d(TAG, "设备管理权限已激活")
//            }
//        }
//    }
    /**
     *gw息屏
     */
    fun gwScreenOff(){
        var  ostype=WonderSp.getDataNomal(this,"ostype");
        KLog.d("屏幕", "关闭gwScreenOff")

//        toast("gwScreenOff"+ostype)
        if (BuildConfig.DEBUG){
            return
        }
        try {
            when (ostype){
                "V001"->   {

                    // 开启屏幕
                    KLog.d("屏幕", "关闭屏幕voo1")

                    TvPictureManager.getInstance().disableBacklight(); //关屏
                }
                "V002"->          {

                    // 开启屏幕
                    KLog.d("屏幕", "关闭屏幕v002")
                    //toast("关闭屏幕v002")
                    val intent = Intent("com.tpv.action.screenSwitch")
                    intent.putExtra("screenSwitch", false)
                    this.sendBroadcast(intent)}

            }
        } catch (e :Exception){
            toast("机器主版本有误")
        }

    }    /**

     * gw亮屏
     */
    fun gwScreenOn(){
        var  ostype=WonderSp.getDataNomal(this,"ostype");
//        toast("gwScreenOn"+ostype)
        KLog.d("屏幕", "打开屏幕gwScreenOn")

        if (BuildConfig.DEBUG){
            return
        }
        try {
            when (ostype){
                "V001"-> {

                    // 开启屏幕
                    KLog.d("屏幕", "打开屏幕voo1")
                    TvPictureManager.getInstance().enableBacklight()};//开屏
                "V002"->          {

                    // 开启屏幕
                    KLog.d("屏幕", "打开屏幕voo2")
                    //toast("打开屏幕voo2")

                    val intent = Intent("com.tpv.action.screenSwitch")
                    intent.putExtra("screenSwitch", true)
                    this.sendBroadcast(intent)}
            }
        }catch (e: Exception){
            toast("机器主版本有误")

        }


    }

//    /**
//     *  判断屏幕是否亮屏
//     */
//    fun  isgwScreenOn(): Boolean{
//        return powerManager?.isScreenOn!!
//    }

    fun  getPass( pass:String,isnet: Boolean){
        if (isnet){
            HttpClient.httpService().getPass().enqueue(object : RequestCallback<List<PassInfor>> {
                override fun onRequestSuccess(body: List<PassInfor>?) {
                    body?.let {
                        if (it.isNotEmpty()) {
                            if (pass.equals(it[0].UnitName)){
                                onBackPressed()
                            }else{
                                toast("密码不正确")
                            }

                        }
                    }
                }

                override fun onRequestFail(error: RequestError) {
                }
            })
        }else{
            if (pass.equals("123")){
                onBackPressed()
            }else{
                toast("密码不正确")
            }
        }

    }

    fun instal(url:String){
        XXPermissions.with(this).permission(permission_array)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: List<String>, all: Boolean) {
                        if (all) {

                            // -1(失败) 0 1（cg） 2(正在下载)
                            if (WonderSp.getDataDownState(this@MyAppCompatActivity)==2){
                                return
                            }
                            WonderSp.setDataDownState(this@MyAppCompatActivity, 2);
                            Thread(object : Runnable{
                                override fun run() {
                                    DownloadUtil.get().download(url,PathUtil.BASE_FILE_URL,"gwesop.apk",object :DownloadUtil.OnDownloadListener{
                                        override fun onDownloadSuccess(file: File?) {
                                            runOnUiThread(object :Runnable{
                                                override fun run() {
                                                    toast("下载完成")
                                                    WonderSp.setDataDownState(this@MyAppCompatActivity, 1);
                                                }
                                            })

                                            KLog.debug(TAG,"onDownloadSuccess")
//                                                                AppUtils.installApk(this@MyAppCompatActivity)
                                            var  ostype=WonderSp.getDataNomal(this@MyAppCompatActivity,"ostype");
                                            when (ostype) {
                                                "V001" -> {
                                                    val intent = Intent()
                                                    intent.action = "com.slx.InstallSlient"
                                                    intent.putExtra("path", PathUtil.BASE_FILE_URL + "/gwesop.apk")
                                                    this@MyAppCompatActivity.sendBroadcast(intent)
                                                }
                                                "V002" -> {
//                                                                        runOnUiThread(object :Runnable{
//                                                                            override fun run() {
//                                                                                toast(PathUtil.BASE_FILE_URL + "/gwesop.apk")                                                                    }
//                                                                        })
                                                    val intent = Intent()
                                                    intent.action="cms.intent.action.UPDATE_APK"
                                                    intent.putExtra("filePath", PathUtil.BASE_FILE_URL + "/gwesop.apk")
                                                    intent.putExtra("keep",true)
                                                    intent.putExtra("packageName", "cn.project.engineering")
                                                    intent.putExtra("activityName", "cn.project.engineering.ui.SplashActivity")
                                                    this@MyAppCompatActivity.sendBroadcast(intent)

                                                }
                                            }
                                            loading=false;
                                        }
                                        override fun onDownloadFailed(e: Exception?) {
                                            runOnUiThread(object :Runnable{
                                                override fun run() {
                                                    toast("下载失败")
                                                    WonderSp.setDataDownState(this@MyAppCompatActivity, -1)
                                                }
                                            })

                                            KLog.debug(TAG,"onDownloadFailed"+e.toString())
                                            loading=false;
                                        }

                                        override fun onDownloading(progress: Int) {
//                                            runOnUiThread(object :Runnable{
//                                                override fun run() {
//                                                    toast("正在下载进度" + progress)
//                                                }
//                                            })

                                            loading=true

                                            KLog.debug(TAG,"onDownloading"+Int)
                                        }

                                    })
                                }
                            }).start()
                        }


                    }

                    override fun onDenied(permissions: List<String>, never: Boolean) {
                        for (i in permissions.indices) {
                            val permission = permissions[i]
                            toast("${permission}权限未允许，请重新选择")
                        }
                    }
                })


    }
    //voo1 就是那个有jar包的
    open fun hideBar() {
        val hideIntent = Intent("com.histar.hideNavigationBar")
        sendBroadcast(hideIntent)
    }

    open fun showBar() {
        val showIntent = Intent("com.histar.showNavigationBar")
        sendBroadcast(showIntent)
    }

    open fun jumpLauncher3() { //
        val jump = Intent(Intent.ACTION_RUN)
        jump.setClassName("com.android.launcher3", "com.android.launcher3.Launcher")
        jump.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        this.startActivity(jump)
    }

    fun getStatusBarHeight(): Int {
        val resources = Resources.getSystem()
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        return resources.getDimensionPixelSize(resourceId)
    }

    fun getNavBarHeight(): Int {
        val res = Resources.getSystem()
        val resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android")
        return if (resourceId != 0) {
            res.getDimensionPixelSize(resourceId)
        } else {
            0
        }
    }

    fun getRealHeight(context: Context): Int {
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val point = Point()
        wm.defaultDisplay.getRealSize(point)
        return point.y
    }
    fun getRealWith(context: Context): Int {
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val point = Point()
        wm.defaultDisplay.getRealSize(point)
        return point.x
    }

    fun isShowNavBar(context: Context?): Boolean {
        if (null == context) {
            return false
        }
        /**
         * 获取应用区域高度
         */
        val outRect1 = Rect()
        try {
            (context as Activity).window.decorView.getWindowVisibleDisplayFrame(outRect1)
        } catch (e: ClassCastException) {
            e.printStackTrace()
            return false
        }
        val activityHeight = outRect1.height()
        val activitywith = outRect1.width()
        KLog.d(TAG,"状态栏高度:" + getStatusBarHeight())
        KLog.d(TAG, "应用区域高度:$activityHeight")
        KLog.d(TAG, "应用区域宽度:$activitywith")
        KLog.d(TAG, "导航栏高度:" + getNavBarHeight())
        KLog.d(TAG, "屏幕物理高度:" + getRealHeight(context))
        KLog.d(TAG, "屏幕物理宽度:" + getRealWith(context))
        /**
         * 屏幕物理高度 - 状态栏高度  导航栏高度 = 导航栏存在时的应用实际高度
         */
        val remainHeight = getRealHeight(context) - getStatusBarHeight() - getNavBarHeight()
        KLog.d(TAG, "导航栏存在时的应用实际高度:" + remainHeight)
        /**
         * 剩余高度跟应用区域高度相等 说明导航栏存在
         */
        return activityHeight == remainHeight
    }
    abstract  fun  netWork(isnet:Boolean)

}